import 'package:flutter/material.dart';
import 'package:flutter_bmfmap_example/service/marketservice.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

class Collectioninfomodel with ChangeNotifier {
  Map<int, Collection> collectionMap =
      CollectionMap(new Map<int, Collection>()).map;

  Future<void> init() async {
    var result = await Marketservice.getcollectionlist();
    // collectionMap.clear();
    collectionMap = CollectionMap.fromJson(result).map;
    print("*****************");
    collectionMap.forEach((int key, Collection value) {
      print(key);
    });
    print("*****************");
    notifyListeners();
  }

  bool iscollection(int id) {
    return collectionMap.containsKey(id);
  }

  void changecollectionstzte(int id) async{
    EasyLoading.show(status: '加载中...');
    if (collectionMap.containsKey(id)) {
      print('remove');
      await Marketservice.deletecollection(id);
    } else {
      print('add');
      await Marketservice.addcollection(id);
    }
    init();
    EasyLoading.dismiss();
  }
}

class CollectionMap {
  final Map<int, Collection> map;

  CollectionMap(this.map);
  factory CollectionMap.fromJson(List<dynamic> itemlist) {
    Map<int, Collection> map = new Map();
    for (var item in itemlist) {
      map[Collection.fromJson(item).commodityId] = Collection.fromJson(item);
    }
    return CollectionMap(map);
  }
}

class Collection {
  int commodityId;
  String name;
  String intro;
  double money;
  int commodityNumber;
  String imgurl1;

  Collection({
    this.commodityId,
    this.name,
    this.intro,
    this.money,
    this.imgurl1,
    this.commodityNumber,
  });

  factory Collection.fromJson(dynamic item) {
    return Collection(
      commodityId: item['commodityId'],
      name: item['name'],
      intro: item['intro'],
      money: item['money'],
      imgurl1: item['imgurl1'],
      commodityNumber: item['commodityNumber'],
    );
  }
}
